package com.base.andlanggl.programs
import android.opengl.GLES20.*
import com.base.andlanggl.util.LangGLTools

/**
 * 纹理着色器
 */
class TextureShaderProgram {
    /**
     * attribute 把属性放进着色器的手段
     * uniform 把属性放进着色器的手段 mat4 4*4矩阵
     * vec2  2个分量坐标 ST纹理坐标 (a_TextureCoordinates)
     * varying 混合颜色 将顶点颜色进行混合
     */
    private val vertexShader:String ="""
        uniform mat4 u_Matrix;
        attribute vec4 a_Position;
        attribute vec2 a_TextureCoordinates;
        varying vec2 v_TextureCoordinates;
        void main(){
            v_TextureCoordinates=a_TextureCoordinates;
            gl_Position= u_Matrix*a_Position;
        }"""

    /**
     *  浮点型精度 mediump ，默认高精度
     *  sampler2D 二维纹理数据数组
     *  varying vec2 2个分量ST 接收顶点着色器传过来的数据
     */
    private val fragmentShader:String ="""
        precision mediump float;
        
        uniform sampler2D u_TextureUnit;
        varying vec2 v_TextureCoordinates;
        
        void main(){
            gl_FragColor= texture2D(u_TextureUnit,v_TextureCoordinates);
        }"""


    private val glProgram:Int=LangGLTools.createProgram(vertexShader,fragmentShader)
    val uMatrixLocation:Int= glGetUniformLocation(glProgram,"u_Matrix")
    val uTextureUnitLocation:Int= glGetUniformLocation(glProgram,"u_TextureUnit")
    val aPositionLocation:Int= glGetAttribLocation(glProgram,"a_Position")
    val aTextureCoordinatesLocation:Int= glGetAttribLocation(glProgram,"a_TextureCoordinates")


    //设置Uniform并返回属性位置
    fun setUniforms(matrix:FloatArray,textureId:Int){
        //传入矩阵数据
        glUniformMatrix4fv(uMatrixLocation,1,false,matrix,0)
        //将活动的纹理单元设置成纹理单元0
        glActiveTexture(GL_TEXTURE0)
        //把纹理绑定这个单元
        glBindTexture(GL_TEXTURE_2D,textureId)
        //然后将选定的这个纹理单元传入片段着色器
        glUniform1i(uTextureUnitLocation,0)
    }

    fun useProgram(){
        glUseProgram(glProgram)//使用程序
    }

}